using System.Collections.Concurrent;
using DmServer.Core.Helper;
using TouchSocket.Core;

namespace DmServer.Handlers;

public class MessageHandlerManager
{
    // 存储客户端与DmSoft实例的映射
    public static ConcurrentDictionary<string, DmSoft> clientDmSoftMap = new ConcurrentDictionary<string, DmSoft>();
    private readonly Dictionary<string, IMessageHandler> _handlers = new Dictionary<string, IMessageHandler>();
    private readonly bool register;
    public MessageHandlerManager(bool register)
    {
        this.register = register;

        RegisterHandler("BindWindowEx", new BindWindowEx());
        RegisterHandler("GetClientSize", new GetClientSize());
        RegisterHandler("GetScreenDataBmp", new GetScreenDataBmp());
        RegisterHandler("MoveTo", new MoveTo());
        RegisterHandler("MoveToEx", new MoveToEx());
        RegisterHandler("MoveWindow", new MoveWindow());
        RegisterHandler("SetClientSize", new SetClientSize());
        RegisterHandler("SetWindowSize", new SetWindowSize());
        RegisterHandler("SetWindowState", new SetWindowState());
        RegisterHandler("SetWindowText", new SetWindowText());
        RegisterHandler("UnBindWindow", new UnBindWindow());
        RegisterHandler("KeyDown", new KeyDown());
        RegisterHandler("KeyDownChar", new KeyDownChar());
        RegisterHandler("KeyPress", new KeyPress());
        RegisterHandler("KeyPressChar", new KeyPressChar());
        RegisterHandler("KeyPressStr", new KeyPressStr());
        RegisterHandler("KeyUp", new KeyUp());
        RegisterHandler("KeyUpChar", new KeyUpChar());
        RegisterHandler("LeftClick", new LeftClick());
        RegisterHandler("LeftDoubleClick", new LeftDoubleClick());
        RegisterHandler("LeftDown", new LeftDown());
        RegisterHandler("LeftUp", new LeftUp());
        RegisterHandler("MiddleClick", new MiddleClick());
        RegisterHandler("MiddleDown", new MiddleDown());
        RegisterHandler("MiddleUp", new MiddleUp());
        RegisterHandler("RightClick", new RightClick());
        RegisterHandler("RightDown", new RightDown());
        RegisterHandler("RightUp", new RightUp());
        RegisterHandler("WheelDown", new WheelDown());
        RegisterHandler("WheelUp", new WheelUp());
    }

    private void RegisterHandler(string method, IMessageHandler handler)
    {
        _handlers.Add(method, handler);
    }

    public void Received(TcpSessionClient client, ReceivedDataEventArgs e)
    {
        string clientId = client.Id;
        string mes = CryptoHelper.DecryptDES( e.ByteBlock.ToArray());

        client.Logger.Info($"已从客户端【{client.Id}】接收到信息：{mes}");

        var request = SerializeConvert.FromJsonString<StringRequestInfo>(mes);

        if (request == null || string.IsNullOrWhiteSpace(request.Method))
            client.SendAsync(CryptoHelper.EncryptDES("协议命令错误！"));

        //client.Send(CryptoHelper.EncryptDES(mes));//将收到的信息直接返回给发送方

        if (_handlers.TryGetValue(request?.Method ?? "", out var handler))
        {
            if (!clientDmSoftMap.TryGetValue(clientId, out DmSoft? dm))
            {
                client.Logger.Error($"dm对象未找到！");
                return;
            }
          
            handler.HandleMessage(request, client, dm);
        }
        else
        {
            client.Logger.Error($"未找到消息处理器: {request?.Method ?? ""}");
            client.SendAsync(CryptoHelper.EncryptDES("协议命令错误！"));
        }
    }

    public void Connected(TcpSessionClient client, ConnectedEventArgs e)
    {
        string clientId = client.Id;
        // 创建新的DmSoft实例并存储
        DmSoft dm = new DmSoft();
        clientDmSoftMap.TryAdd(clientId, dm);
        client.Logger.Info($"Client : {clientId} connected. DmSoft instance created.");

        if (!register)
        {
            client.Logger.Error($"插件免注册失败！");
            client.SendAsync(client.Id, CryptoHelper.EncryptDES("插件免注册失败！"));
            return;
        }

        if (!clientDmSoftMap.TryGetValue(clientId, out DmSoft? dm1))
        {
            client.Logger.Error($"dm对象未找到！");
            client.SendAsync(client.Id, CryptoHelper.EncryptDES("创建对象失败！"));
            return;
        }

        var message = "";

        message = $"【{client.Id}】" + "调用插件：" + register;
        client.SendAsync(client.Id, CryptoHelper.EncryptDES(message));

        var ver = dm1.Ver();//版本号
        message = $"【{client.Id}】" + "版本号：" + ver;
        client.Logger.Info(message);

        var regcharge = dm1.Reg(DmConfig.DmRegCode, DmConfig.DmVerInfo);// 收费注册
        message = $"【{client.Id}】" + "收费注册：" + regcharge;
        client.Logger.Info(message);

        message = regcharge == 1 ? "插件初始化成功！" : "插件初始化失败！";
        client.SendAsync(client.Id, CryptoHelper.EncryptDES(message));
    }

    public void Disconnected(TcpSessionClient client,ClosedEventArgs e)
    {
        string clientId = client.Id;
        // 移除DmSoft实例
        clientDmSoftMap.TryRemove(clientId, out _);
        client.Logger.Info($"Client : {clientId} disconnected. DmSoft instance removed.");
    }

}
